package com.bvgol.examples.nio;/**
 * @Classname TestFileChannleReadAndWrite
 * @Description TODO
 * @Date 2021/6/17 17:57
 * @Created by GUOCHEN
 */

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @program: my-spring-completely
 * @description:
 * @author: GUOCHEN
 * @create: 2021/06/17 17:57
 */
public class TestFileChannleReadAndWrite {
    public static void main(String[] args) throws Exception {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream("D:\\idea_projects\\my-springboot-completely\\netty\\src\\main\\resources\\file01.txt");
            FileChannel inputStreamChannel = fileInputStream.getChannel();

            fileOutputStream = new FileOutputStream("D:\\idea_projects\\my-springboot-completely\\netty\\src\\main\\resources\\file04.txt");
            FileChannel outputStreamChannel = fileOutputStream.getChannel();

            //一次将文件全部读取到内存 大文件不能这么搞
            ByteBuffer allocate = ByteBuffer.allocate(fileInputStream.available());

            while (true){
                int read = inputStreamChannel.read(allocate);
                System.out.println("read = " + read);
                if (read==-1){
                    break;
                }
                //翻转buffer
                allocate.flip();

                outputStreamChannel.write(allocate);

                //当前循环执行完毕重置参数(必须)
                allocate.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fileInputStream!=null){fileInputStream.close();}
            if(fileOutputStream!=null){fileOutputStream.close();}
        }

    }
}
